using Quartz;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Text.RegularExpressions;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.ScheduleJob.Dao;
using T.FAS.Runtime.ScheduleJob.Manager;
using T.ServiceComponent.Config.Client;
using T.ServiceComponent.DataAccessEx.Core;

namespace T.FAS.Runtime.ScheduleJob.Service
{
    /// <summary>
    /// 配置帮助
    /// </summary>
    public class ConfigHelper
    {
        public const string QueartzConfigKey = "FAS.ScheduleJob.Properties";
        public const string FasDBConnKey = "TTP.Database.TFAS.ConnectionString";
        private static readonly ConfigMode s_configMode;
        public static ConfigMode ConfigMode
        {
            get
            {
                return s_configMode;
            }
        }

        static ConfigHelper()
        {
            var modeStr = ConfigurationManager.AppSettings.Get("isDelFirst");
            if (Enum.TryParse(modeStr, out ConfigMode result))
            {
                s_configMode = result;
            }
            else
            {
                s_configMode = ConfigMode.ConfigCenter;
            }
        }

        public static NameValueCollection GetQuartzConfig()
        {
            var cfgText = ConfigManager.GetConfigValue(QueartzConfigKey);
            if (string.IsNullOrEmpty(cfgText))
            {
                throw new Exception($"Failed to get Quartz Config from ConfigCenter ");
            }
            return GetQuartzConfigFromText(cfgText);
        }

        private static NameValueCollection GetQuartzConfigFromText(string cfgText)
        {
            if (string.IsNullOrEmpty(cfgText)) return default;
            string[] configArray = cfgText.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
            NameValueCollection nameValueCollection = new NameValueCollection();

            foreach (var text in configArray)
            {
                if (!text.StartsWith("#"))
                {
                    if (text.StartsWith("!END"))
                    {
                        break;
                    }

                    string[] array = text.Split(new char[1] { '=' }, 2);
                    if (array.Length == 2)
                    {
                        string attrKey = array[0].Trim();
                        nameValueCollection[attrKey] = array[1].Trim();
                    }
                }
            }
            var cfgValue = ConfigManager.GetConfigValue(FasDBConnKey);
            if (string.IsNullOrEmpty(cfgValue))
            {
                throw new Exception($"Failed to get FAS DB ConnectionString ");
            }
            string result = GetDatabaseConnectStr(cfgValue);
            nameValueCollection["quartz.dataSource.myDS.connectionString"] = result;
            return nameValueCollection;
        }

        private static string GetDatabaseConnectStr(string connStr)
        {
            if (string.IsNullOrEmpty(connStr))
            {
                throw new ArgumentNullException(nameof(connStr));
            }

            Dictionary<string, string> dict = new Dictionary<string, string>();
            foreach (var pair in connStr.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                string[] keyValue = pair.Split(new[] { '=' }, 2);
                if (keyValue.Length == 2)
                {
                    string key = keyValue[0].Trim();
                    string value = keyValue[1].Trim();
                    dict[key] = value;
                }
            }
            var db = new ScheduleJobInstanceDao().DB;
            if (db?.DbType == TDbType.PostgreSQL)
            {
                if (dict.ContainsKey("server") && dict.ContainsKey("port") && dict.ContainsKey("database") && dict.ContainsKey("user id") && dict.ContainsKey("password"))
                    return $"Host={dict["server"]};Port={dict["port"]};Database={dict["database"]};Username={dict["user id"]};Password={dict["password"]};";
            }
            else if (db?.DbType == TDbType.MySql)
            {
                return $"data source={dict["data source"]};database={dict["database"]};user id={dict["user id"]};password={dict["password"]};port={dict["port"]};CharSet=utf8mb4";
            }
            return connStr;
        }

    }

    public enum ConfigMode
    {
        ConfigCenter = 0,
        Local = 1,
    }
}
